package com.zm.admin.zmeng.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zm.admin.config.RabbitConfig;
import com.zm.admin.utils.ResultBean;
import com.zm.admin.zmeng.domain.ZmNotice;
import com.zm.admin.zmeng.domain.ZmNoticeUser;
import com.zm.admin.zmeng.domain.ZmUser;
import com.zm.admin.zmeng.dto.NoticeDto;
import com.zm.admin.zmeng.mapper.ZmNoticeMapper;
import com.zm.admin.zmeng.mapper.ZmNoticeUserMapper;
import com.zm.admin.zmeng.mapper.ZmUserMapper;
import com.zm.admin.zmeng.service.ZmNoticeService;
import com.zm.admin.zmeng.service.ZmNoticeUserService;
import com.zm.admin.zmeng.service.ZmUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/***
 *
 * @Auther: MuYun
 * @Date: 2024/4/10 16:30
 * @Description：通知公告模块相关接口
 *
 */
@RestController
@Slf4j
@RequestMapping("/notice")
public class NoticeController {

    @Resource
    private ZmNoticeService zmNoticeService;

    @Resource
    private ZmNoticeUserService zmNoticeUserService;

    @Resource
    private ZmNoticeUserMapper zmNoticeUserMapper;

    @Resource
    private ZmUserMapper zmUserMapper;

    @Resource
    private RabbitTemplate rabbitTemplate;

    /**
     * 获取列表数据(支持模糊查询
     * @param zmNotice
     * @return
     */
    @RequestMapping("/list")
    public ResultBean list(NoticeDto zmNotice){
        ResultBean resultBean=new ResultBean();
        try{
            QueryWrapper<ZmNotice> wrapper = designWrapper(zmNotice);
            Integer pageNo=1;
            Integer pageSize=10;
            if(ObjectUtil.isNotEmpty(zmNotice.getPageNo())){
                pageNo=zmNotice.getPageNo();
            }
            if(ObjectUtil.isNotEmpty(zmNotice.getPageSize())){
                pageSize=zmNotice.getPageSize();
            }
            Page<ZmNotice> page = zmNoticeService.page(new Page<>(pageNo, pageSize), wrapper);
            resultBean.setData(page).setCode(ResultBean.CODE_SUCCESS);
        }catch (Exception e){
            log.error("获取公告列表数据失败:{}",e);
            resultBean.setCode(ResultBean.CODE_ERROR).setMsg("获取公告列表数据失败");
        }
        return resultBean;
    }

    /**
     * 获取列表数据(只查最近7条
     * @param
     * @return
     */
    @RequestMapping("/query")
    public ResultBean query(){
        ResultBean resultBean=new ResultBean();
        try{
            QueryWrapper<ZmNotice> wrapper = new QueryWrapper<>();
            List<ZmNotice> zmNoticeList = zmNoticeService.list(
                    wrapper.lambda().orderByDesc(ZmNotice::getCreateTime));
            resultBean.setCode(ResultBean.CODE_SUCCESS).setData(zmNoticeList);
        }catch (Exception e){
            log.error("获取列表数据接口出错:{}",e);
            resultBean.setCode(ResultBean.CODE_ERROR);
        }
        return resultBean;
    }

    /**
     * 查询未阅读公告
     * @param zmNoticeUser
     * @return
     */
    @RequestMapping("/queryNoRead")
    public ResultBean query(ZmNoticeUser zmNoticeUser){
        ResultBean resultBean=new ResultBean();
        try{
            //获取全部公告
            QueryWrapper<ZmNotice> wrapper=new QueryWrapper<>();
            List<ZmNotice> zmNotices = zmNoticeService.list(wrapper.lambda().eq(ZmNotice::getType, "已发布"));
            List<String> noticeList = zmNotices.stream().map(ZmNotice::getId).collect(Collectors.toList());
            //获取该用户已读取公告
            QueryWrapper<ZmNoticeUser> wrapper1=new QueryWrapper<>();
            List<ZmNoticeUser> zmNoticeUsers = zmNoticeUserService.list(wrapper1.lambda().eq(ZmNoticeUser::getUserId, zmNoticeUser.getUserId()));
            List<String> readList = zmNoticeUsers.stream().map(ZmNoticeUser::getNoticeId).collect(Collectors.toList());
            //筛选未读取公告
            if(readList.size()!=0){
                List<String> noReadList = noticeList.stream()
                        .filter(i -> !readList.contains(i)).collect(Collectors.toList());
                resultBean.setCode(ResultBean.CODE_SUCCESS).setData(noReadList);
            }else {
                resultBean.setCode(ResultBean.CODE_SUCCESS).setData(noticeList);
            }
        }catch (Exception e){
            log.error("查询未阅读公告接口报错:{}",e.getMessage());
            resultBean.setCode(ResultBean.CODE_ERROR);
        }
        return resultBean;
    }

    /**
     * 查阅公告
     * @param zmNotice
     * @return
     */
    @RequestMapping("/read")
    public ResultBean read(ZmNotice zmNotice){
        ResultBean resultBean=new ResultBean();
        try{
            String id = StpUtil.getLoginIdAsString();
            ZmNoticeUser zmNoticeUser=new ZmNoticeUser();
            zmNoticeUser.setNoticeId(zmNotice.getId());
            zmNoticeUser.setUserId(id);
            zmNoticeUser.setReadtime(DateUtil.now());
            zmNoticeUserMapper.insert(zmNoticeUser);
            resultBean.setCode(ResultBean.CODE_SUCCESS).setMsg("查阅公告成功");
        }catch (Exception e){
            log.error("公告查阅接口报错:{}",e);
            resultBean.setCode(ResultBean.CODE_ERROR);
        }
        return resultBean;
    }

    /**
     * 新增公告
     * @param zmNotice
     * @return
     */
    @RequestMapping("/add")
    public ResultBean add(ZmNotice zmNotice){
        ResultBean resultBean=new ResultBean();
        try{
            String loginId = StpUtil.getLoginIdAsString();
            if(StrUtil.isNotEmpty(loginId)){
                ZmUser zmUser = zmUserMapper.selectById(loginId);
                zmNotice.setCreateBy(zmUser.getUsername());
            }else {
                zmNotice.setCreateBy("未知用户");
            }
            zmNotice.setCreateTime(DateUtil.date());
            zmNoticeService.save(zmNotice);
            if("已发布".equals(zmNotice.getType())){
                releaseNotice(zmNotice);
            }
            resultBean.setCode(ResultBean.CODE_SUCCESS).setMsg("发布公告成功");
        }catch (Exception e){
            log.error("新增公告出错:{}",e);
            resultBean.setCode(ResultBean.CODE_ERROR);
        }
        return resultBean;
    }

    /**
     * 修改公告
     * @param zmNotice
     * @return
     */
    @RequestMapping("/update")
    public ResultBean update(ZmNotice zmNotice){
        ResultBean resultBean=new ResultBean();
        try {
            zmNotice.setUpdateBy(StpUtil.getLoginIdAsString());
            zmNotice.setUpdateTime(DateUtil.date());
            zmNoticeService.updateById(zmNotice);
            if("已发布".equals(zmNotice.getType())){
                releaseNotice(zmNotice);
            }
            resultBean.setCode(ResultBean.CODE_SUCCESS);
        }catch (Exception e){
            log.error("修改公告接口出错：{}",e);
            resultBean.setCode(ResultBean.CODE_ERROR);
        }
        return resultBean;
    }

    /**
     * 删除公告
     * @param zmNotice
     * @return
     */
    @RequestMapping("/del")
    public ResultBean del(ZmNotice zmNotice){
        ResultBean resultBean=new ResultBean();
        try {
            zmNoticeService.removeById(zmNotice.getId());
            resultBean.setCode(ResultBean.CODE_SUCCESS);
        }catch (Exception e){
            log.error("删除公告接口出错：{}",e);
            resultBean.setCode(ResultBean.CODE_ERROR);
        }
        return resultBean;
    }

    public void releaseNotice(ZmNotice zmNotice){
        rabbitTemplate.convertAndSend(RabbitConfig.EXCHANGE_N,
                RabbitConfig.RK_N,
                zmNotice.getCreateBy());
    }

    public QueryWrapper<ZmNotice> designWrapper(NoticeDto zmNotice){
        QueryWrapper<ZmNotice> wrapper=new QueryWrapper<>();
        if(ObjectUtil.isNotEmpty(zmNotice.getTitle())){
            wrapper.lambda().like(ZmNotice::getTitle,zmNotice.getTitle());
        }
        if(ObjectUtil.isNotEmpty(zmNotice.getEndTime())){
            wrapper.lambda().le(ZmNotice::getCreateTime,zmNotice.getEndTime());
        }
        if(ObjectUtil.isNotEmpty(zmNotice.getStartTime())){
            wrapper.lambda().ge(ZmNotice::getCreateTime,zmNotice.getStartTime());
        }
        return wrapper;
    }
}
